package com.sanda.androidcourse.chapter07;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;

public class MyServiceUseStart extends Service {

    public static final String ServiceTAG = "MyService";

    private Handler handler = new Handler(Looper.getMainLooper());
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Log.d(ServiceTAG, "Service is running...");
            handler.postDelayed(this, 5000); // 每5秒打印一次日志
        }
    };
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(ServiceTAG, "Service Created");
        Toast.makeText(this, "Service Created", Toast.LENGTH_SHORT).show();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(ServiceTAG, "Service Started");
        // 在此执行长时间运行的任务，例如：后台任务
        Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
        handler.post(runnable);
        return START_STICKY;  // 如果服务被杀死，系统会重新创建
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.d(ServiceTAG, "Service Bound");
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(ServiceTAG, "Service Destroyed");
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();
        handler.removeCallbacks(runnable);
    }

}
